package leetcode.sort;

public class QuickSort {
    public void swap(int[] nums, int left, int right) {
        int tmp = nums[left];
        nums[left] = nums[right];
        nums[right] = tmp;
    }

    public int[] quick_sort_1(int[] nums, int begin, int end) {
        if (end < begin) {
            return nums;
        }
        int left = begin;
        int right = end;
        int key = begin;

        while (left < right) {
            while (left < right && nums[right] >= nums[key]) {
                right--;
            }
            while (left < right && nums[left] <= nums[key]) {
                left++;
            }
            if (left < right) {
                swap(nums, left, right);
            }
        }
        int meet = left;
        swap(nums, key, meet);
        quick_sort_1(nums, 0, meet - 1);
        quick_sort_1(nums, meet + 1, end);
        return nums;
    }

    public int[] quick_sort_2(int[] nums, int begin, int end) {
        if (begin > end) {
            return nums;
        }
        int left = begin;
        int right = end;
        int key = nums[left];
        while (left < right) {
            while (left < right && nums[right] >= key) {
                right--;
            }
            nums[left] = nums[right];
            while (left < right && nums[left] <= key) {
                left++;
            }
            nums[right] = nums[left];
        }
        int meet = left;
        nums[meet] = key;
        quick_sort_2(nums, begin, meet - 1);
        quick_sort_2(nums, meet + 1, end);
        return nums;
    }


    public int[] qucik_sort_3(int[] nums, int begin, int end) {
        if (begin > end) {
            return nums;
        }
        int pre = begin;
        int cur = begin + 1;
        int key = begin;

        while (cur <= end) {
            if (nums[cur] < nums[key] && ++pre != cur) {
                swap(nums, pre, cur);
            }
            cur++;
        }
        int meet = pre;
        swap(nums, pre, key);
        qucik_sort_3(nums, begin, meet - 1);
        qucik_sort_3(nums, meet + 1, end);
        return nums;
    }


    public static void main(String[] args) {
        QuickSort quickSort = new QuickSort();
        int[] arr = new int[]{1, 3, 5, 7, 3, 9, 6, 3};
        //方法1
        int[] ret1 = quickSort.quick_sort_1(arr, 0, arr.length - 1);
        for (int i : ret1) {
            System.out.print(i + " ");
        }
        System.out.println();

        //方法2
        int[] ret2 = quickSort.quick_sort_2(arr, 0, arr.length - 1);
        for (int i : ret2) {
            System.out.print(i + " ");
        }
        System.out.println();

        //方法3
        int[] ret3 = quickSort.qucik_sort_3(arr, 0, arr.length - 1);
        for (int i : ret3) {
            System.out.print(i + " ");
        }
    }
}
